from ast import Try
import os,sys
import serial
import time
import json

serialDelay = 0.02

def getSerialConfig():
    f = open('config.txt','r')
    dat = f.read()
    f.close()
    tmpdict = json.loads(dat)
    return tmpdict
def sendAndRead(cmd):
    # sendAndread
    t.write(cmd)
    t.flush()
    time.sleep(serialDelay)

    # readcom
    n = t.inWaiting()
    while n<=0:
        time.sleep(serialDelay)
        n = t.inWaiting()
    pstr = t.read(n).decode()
    print(f'readcom = {pstr}')


conf = getSerialConfig()
port = conf['port']
btv = conf['btv']
t = serial.Serial(port,btv,timeout=1)

print(f'串口名        {t.name}\n')             
print(f'串口号        {t.port}')             
print(f'波特率        {t.baudrate}')         
print(f'字节大小       {t.bytesize}')       
print(f'校验位N       {t.parity} －无校验，E－偶校验，O－奇校验')        
print(f'停止位        {t.stopbits}')          
print(f'读超时设置      {t.timeout}')       
print(f'写超时        {t.writeTimeout}')      
print(f'软件流控       {t.xonxoff}')         
print(f'硬件流控       {t.rtscts}')          
print(f'硬件流控       {t.dsrdtr}')          
print(f'字符间隔超时     {t.interCharTimeout}')  
print('-'*10)
time.sleep(1)


# https://www.rapidtables.com/convert/number/hex-to-decimal.html
# https://www.rapidtables.com/convert/number/decimal-to-hex.html

# 格式: [9个Bytes]
#   B1    B2 B3                     B4 B5         B6    B7     B8 B9
#   抬起   x方向 (-126-126) & 速度    y..          滚轮x  滚轮y   无用
#   00    0f 01                     00 00         00    00     0000

# 问题1,  连接一段时间后, 设备与苹果手机断开连接, 蓝牙设备里点击连接无效, 需要对设备断电再插上电脑

# 问题2,  向右移动10,再向左移动10, 成功回到原点. 但是接下来的点击命令, 造成了意外的鼠标移动
#   问题原因 - 以下点击/抬起操作,似乎会重复最后一次移动命令 也就是向左移10
#   readcom = 010000000000000000 点击 
#   readcom = 000000000000000000 抬起

import struct


# hex_value = struct.pack('b', -10).hex()

# print(hex_value)
# 将-10转换为一个字节的16进制表示
def getHexWithNum(p):
    hex_value = struct.pack('b', -10).hex()
    print(type(hex_value),hex_value)
    return hex_value

d = getHexWithNum(-10)
print(d)

cmd = ('[00' + '0a' + '09' + '00' + '00'+ '00' + '00' + '0000]').encode() # 向右移动10
sendAndRead(cmd)

cmd = ('[00' + 'f6' + '09' + '00' + '00'+ '00' + '00' + '0000]').encode() # 向左移动10 
sendAndRead(cmd)



cmd = ('[01' + '0000' + '0000' + '0000' + '0000]').encode() # 点击 
sendAndRead(cmd)
cmd = ('[00' + '0000' + '0000' + '0000' + '0000]').encode() # 抬起
sendAndRead(cmd)

t.close()

